package com.sky.service.impl;

import com.atom.module.common.result.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.common.constant.StatusConstant;
import com.sky.pojo.dto.DishDTO;
import com.sky.pojo.dto.DishPageQueryDTO;
import com.sky.pojo.entity.Dish;
import com.sky.pojo.entity.DishFlavor;
import com.sky.pojo.entity.SetMeal;
import com.sky.pojo.entity.SetMealDish;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.service.DishService;
import com.sky.pojo.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;

@Slf4j
@Service
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Autowired
    private SetMealDishMapper setmealDishMapper;

    @Autowired
    private SetMealMapper setmealMapper;


    @Override
    public void addDish(DishDTO dto) {
        // 1.构造菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        // 拷贝属性值
        BeanUtils.copyProperties(dto, dish);
        // 调用mapper保存方法
        dishMapper.insert(dish);
        log.info("dishId={}", dish.getId());

        // 2.构造菜品口味列表数据，将其存入dish_flavor表中
        List<DishFlavor> dishFlavorList = dto.getFlavors();
        if (dishFlavorList != null && !dishFlavorList.isEmpty()) {
            // 2.1关联菜品id
            dishFlavorList.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            // 2.2 调用mapper保存方法,批量插入口味列表数据
            dishFlavorMapper.insertBatch(dishFlavorList);
        }
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishes = dishMapper.listBy(dish);

        if (dishes == null || dishes.isEmpty()) {
            return Collections.emptyList();
        }

        return dishes.stream().map(new Function<Dish, DishVO>() {
            @Override
            public DishVO apply(Dish dish) {

                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(dish, dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(dish.getId());
                dishVO.setFlavors(flavors);

                return dishVO;
            }
        }).toList();
    }

    @Override
    public List<DishVO> delete(List<Long> ids) {
        // 查询 排除 起售的菜品
        List<Dish> list = ids.stream().map(new Function<Long, Dish>() {
            @Override
            public Dish apply(Long id) {
                return dishMapper.selectById(id);
            }
        }).filter(new Predicate<Dish>() {
            @Override
            public boolean test(Dish dish) {
                if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                    return false;
                }
                SetMealDish byDishId = setmealDishMapper.getByDishId(dish.getId());
                if (byDishId != null) {
                    return false;
                }
                return true;
            }
        }).toList();

        if (list.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> deleteList = list.stream().map(Dish::getId).toList();
        // 3.删除菜品基本信息 dish表
        dishMapper.deleteBatch(deleteList);

        // 4.删除菜品口味列表信息 dish_flavor表
        dishFlavorMapper.deleteBatch(deleteList);

        // 进行删除,并返回删除结果 ,以便上层能够进行刷新redis
        return list.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dishVO, dish);
            return dishVO;
        }).toList();
    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        // 1.设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        // 2.调用mapper的列表查询方法，强转成Page
        Page<DishVO> page = dishMapper.list(dto);

        // 3.封装PageResult对象并返回
        return new PageResult(page.getResult(), page.getTotal());
    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();

        // 1.根据菜品id查询菜品基本信息,封装到dishVO中
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);

        // 2.根据菜品id查询口味列表数据,封装到dishVO中
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);

        // 3.返回DishVO对象
        return dishVO;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if (status.equals(StatusConstant.DISABLE)) {
            // 联表查询setmeal、dish、setmeal_dish
            List<SetMeal> setmealList = setmealMapper.getByDishId(id);
            for (SetMeal setmeal : setmealList) {
                if (setmeal != null) {  //有关联的套餐才需要执行update操作，注意判空处理，否则NPE
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    @Override
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);

        // 1.修改菜品的基本信息，dish表
        dishMapper.update(dish);

        // 2.修改口味列表信息，dish_flavor表
        // 由于口味数据可能增加、可能删除、还可能修改口味的值，涉及到增删改操作，所以先全部删除旧数据，再添加新数据
        dishFlavorMapper.deleteByDishId(dto.getId());

        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 关联菜品id
            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId, String name) {
        return dishMapper.getByCategoryId(categoryId, name);
    }
}
